

import React,{useState,useEffect} from 'react'
import { Button,Dropdown,Menu } from 'antd'
import {getResourceButtons} from '@utils/store'
import './index.css'

const sliceBtns = (btns ,maxNums=3)=>{
  let list = getResourceButtons()||[]
  let btn = btns.filter(it=>!it.isHide).filter(it=>{
    // return true
    return !it.permission || list?.find(i=>i.permission===it.permission)
  })
  let moreBtn=btn.splice(maxNums)
  return {
    moreBtn:moreBtn,
    permissionBtns:btn
  }
}
export default ({btns=[],maxNums=3})=>{
  let {moreBtn,permissionBtns} = sliceBtns(btns,maxNums) 
  let [permissionBtn,setBtns] = useState(permissionBtns)
  let [subMenu,setSubMenu] = useState(()=>{
    if(moreBtn.length==0) return null
    return <Menu>
      {
        moreBtn.map((item,index)=>{
          return <Menu.Item key={index}>
              <div onClick={_=>{
                item.onClick()
              }} >
                {item.text}
              </div>
            </Menu.Item>
        })
      }
    </Menu>
  })
  useEffect(()=>{
    let {moreBtn,permissionBtns} = sliceBtns(btns,maxNums) 
    setBtns(permissionBtns)
    setSubMenu(()=>{
      if(moreBtn.length==0) return null
      return <Menu>
        {
          moreBtn.map((item,index)=>{
            return <Menu.Item key={index}>
                <div onClick={_=>{
                  item.onClick()
                }} >
                  {item.text}
                </div>
              </Menu.Item>
          })
        }
      </Menu>
    })
  },[btns])
  return <div className='group-btn-control'>
    {
      permissionBtn.map((it,index)=>{
        return <Button key={'group-btns'+index}  size="small"  type={'dashed'} onClick={_=>{
          it.onClick()
        }}>{it.text}</Button>
      })
    }
    {subMenu?<Dropdown size={'small'}   overlay={subMenu} placement="bottomLeft">
      <Button>{'···'}</Button>
    </Dropdown>:null}
  </div>
}

